import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/models/merchant_user.dart';
import 'package:merchants/providers/providers.dart';

class MerchantUserManagementScreen extends ConsumerStatefulWidget {
  const MerchantUserManagementScreen({super.key});

  @override
  MerchantUserManagementScreenState createState() =>
      MerchantUserManagementScreenState();
}

class MerchantUserManagementScreenState
    extends ConsumerState<MerchantUserManagementScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  List<MerchantUser> _merchantUsers = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _fetchStaff();
  }

  Future<void> _fetchStaff() async {
    setState(() => _isLoading = true);
    try {
      _merchantUsers =
          await ref.read(merchantUserServiceProvider).getStaffList();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('加载员工失败：$e')));
      }
    }
    if (mounted) {
      setState(() => _isLoading = false);
    }
  }

  Future<void> _approveStaff(MerchantUser merchantUser) async {
    if (!mounted) return;
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            title: const Text(
              '确认通过',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            content: Text(
              '确定要通过 ${merchantUser.name} 加入 ${merchantUser.name} 的申请吗？\n通过后，该员工将获得店铺管理权限。',
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: Text('取消', style: TextStyle(color: Colors.grey[600])),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                child: Text(
                  '确认',
                  style: TextStyle(
                    color: Theme.of(context).primaryColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
    );

    if (confirmed == true) {
      setState(() => _isLoading = true);
      try {
        await ref
            .read(merchantUserServiceProvider)
            .approveStaff(merchantUser.id!);
        await _fetchStaff(); // 刷新列表
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('已通过申请')));
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('操作失败：$e')));
        }
      }
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Widget _buildStaffItem(MerchantUser merchantUser) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    merchantUser.name,
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '申请店铺：${merchantUser.name}',
                    style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '状态：${merchantUser.status == 'pending' ? '申请中' : '已加入'}',
                    style: TextStyle(
                      fontSize: 14,
                      color:
                          merchantUser.status == 'pending'
                              ? Colors.orange[700]
                              : Theme.of(context).primaryColor,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
            if (merchantUser.status == 'pending')
              ElevatedButton(
                onPressed: () => _approveStaff(merchantUser),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).primaryColor,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 8,
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  elevation: 0,
                ),
                child: const Text(
                  '通过申请',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
                ),
              ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('员工管理'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.transparent,
        bottom: TabBar(
          controller: _tabController,
          labelColor: Theme.of(context).primaryColor,
          unselectedLabelColor: Colors.grey,
          indicatorColor: Theme.of(context).primaryColor,
          tabs: const [Tab(text: '申请中'), Tab(text: '全部员工'), Tab(text: '已加入')],
        ),
      ),
      body: SafeArea(
        child:
            _isLoading
                ? const Center(child: CircularProgressIndicator())
                : TabBarView(
                  controller: _tabController,
                  children: [
                    // 申请中
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child:
                          _merchantUsers
                                  .where(
                                    (merchantUser) =>
                                        merchantUser.status == 'pending',
                                  )
                                  .isEmpty
                              ? const Center(
                                child: Text(
                                  '暂无申请中的员工',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.grey,
                                  ),
                                ),
                              )
                              : ListView.builder(
                                itemCount:
                                    _merchantUsers
                                        .where(
                                          (merchantUser) =>
                                              merchantUser.status == 'pending',
                                        )
                                        .length,
                                itemBuilder:
                                    (context, index) => _buildStaffItem(
                                      _merchantUsers
                                          .where(
                                            (merchantUser) =>
                                                merchantUser.status ==
                                                'pending',
                                          )
                                          .toList()[index],
                                    ),
                              ),
                    ),
                    // 全部员工
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child:
                          _merchantUsers.isEmpty
                              ? const Center(
                                child: Text(
                                  '暂无员工',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.grey,
                                  ),
                                ),
                              )
                              : ListView.builder(
                                itemCount: _merchantUsers.length,
                                itemBuilder:
                                    (context, index) =>
                                        _buildStaffItem(_merchantUsers[index]),
                              ),
                    ),
                    // 已加入
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child:
                          _merchantUsers
                                  .where(
                                    (merchantUser) =>
                                        merchantUser.status == 'approved',
                                  )
                                  .isEmpty
                              ? const Center(
                                child: Text(
                                  '暂无已加入员工',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.grey,
                                  ),
                                ),
                              )
                              : ListView.builder(
                                itemCount:
                                    _merchantUsers
                                        .where(
                                          (merchantUser) =>
                                              merchantUser.status == 'approved',
                                        )
                                        .length,
                                itemBuilder:
                                    (context, index) => _buildStaffItem(
                                      _merchantUsers
                                          .where(
                                            (merchantUser) =>
                                                merchantUser.status ==
                                                'approved',
                                          )
                                          .toList()[index],
                                    ),
                              ),
                    ),
                  ],
                ),
      ),
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}
